/**
 * Created by Ysssssss on 2021/4/22.
 */
import React, { useCallback, useState } from 'react'
import { DatePicker } from "antd";
import dayjs from "dayjs";

const DateRangeUnlimitedPicker = props => {
    const { startDate, endDate, beforeNow, afterNow, onChange, style, className} = props

    const handleChange = useCallback(([startDateMoment, endDateMoment]) => {
        onChange({
            startDate: dayjs(startDateMoment).format('YYYY-MM-DD'),
            endDate: dayjs(endDateMoment).format('YYYY-MM-DD')
        })
    }, [onChange])

    const disabledDate = useCallback((current) => {
        if (!current) return true;
        if (beforeNow && current >= dayjs().endOf('day')) return true
        if (afterNow && current <= dayjs().endOf('day')) return true
    })

    return (
        <DatePicker.RangePicker
            className={className}
            style={style}
            value={!startDate && !endDate ? [] : [dayjs(startDate), dayjs(endDate)]}
            onChange={handleChange}
            disabledDate={disabledDate}
        />
    )
}

const DateRangeLimitedPicker = props => {
    const { startDate, endDate, dateRange, beforeNow, afterNow, onChange, style, className} = props
    const [dates, setDates] = useState([]);
    const [hackValue, setHackValue] = useState();

    const handleChange = useCallback(([startDateMoment, endDateMoment]) => {
        onChange({
            startDate: dayjs(startDateMoment).format('YYYY-MM-DD'),
            endDate: dayjs(endDateMoment).format('YYYY-MM-DD')
        })
    }, [onChange])

    const disabledDate = (current) => {
        if (!current) return true;
        if (beforeNow && current >= dayjs().endOf('day')) return true
        if (afterNow && current <= dayjs().endOf('day')) return true
        if (!dates || dates.length === 0) {
            return false;
        }
        const tooLate = dates[0] && current.diff(dates[0], 'days') > dateRange;
        const tooEarly = dates[1] && dates[1].diff(current, 'days') > dateRange;
        return tooEarly || tooLate;
    }

    const onOpenChange = open => {
        if (open) {
            setHackValue([]);
            setDates([]);
        } else {
            setHackValue(undefined);
        }
    };

    return (
        <DatePicker.RangePicker
            className={className}
            style={style}
            value={hackValue || [dayjs(startDate), dayjs(endDate)]}
            onChange={handleChange}
            disabledDate={disabledDate}
            onCalendarChange={val => setDates(val)}
            onOpenChange={onOpenChange}
        />
    )
}

const DateRangePicker= ({value, ...props}) => props.dateRange ?
    <DateRangeLimitedPicker
        {...props}
        {...(value || {})}
    /> :
    <DateRangeUnlimitedPicker
        {...props}
        {...(value || {})}
    />

export default DateRangePicker